package secondriver.spark.core.impl;

import secondriver.spark.core.SparkHandler;
import secondriver.spark.route.LoginRoute;
import secondriver.spark.template.FreeMarkerTemplateEngineFactory;
import spark.ModelAndView;
import spark.Request;
import spark.Response;
import spark.Route;
import spark.Session;
import spark.Spark;
import spark.TemplateViewRoute;

public class DefaultSparkHandler implements SparkHandler {

	public void init() {
		this.setGetMethod();
		this.setPostMethod();
	}

	private void setGetMethod() {

		// 普通方式
		Spark.get("/", new Route() {

			@Override
			public Object handle(Request request, Response response) {
				response.redirect("/index", 304);
				return this;
			}
		});

		// 闭包方式
		Spark.get("/index", (Request request, Response response) -> {
			return "Welcome !";
		});

		// 登录
		Spark.get("/l/:u/:p", new LoginRoute());

		Spark.get("/index.jsp", new Route() {

			@Override
			public Object handle(Request request, Response response) {
				// TODO Auto-generated method stub
				return this;
			}
		});

		// FreeMarkerTemplate视图处理
		Spark.get("/hello", new TemplateViewRoute() {

			@Override
			public ModelAndView handle(Request request, Response response) {
				ModelAndView mav = new ModelAndView(null, "/hello.tpl");
				return mav;
			}
		}, FreeMarkerTemplateEngineFactory.getFreeMarkerEngine());

		Spark.get("/throwexception", (request, response) -> {
			try {
				throw new Exception();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			return request;
		});

	}

	private void setPostMethod() {

		// 注册
		Spark.post("/r", new Route() {

			@Override
			public Object handle(Request request, Response response) {
				String u = (String) request.raw().getParameter("u");
				String p = (String) request.raw().getParameter("p");
				System.out.println(u);
				System.out.println(p);
				Session session = request.session();
				session.attribute("u", u);
				session.attribute("p", p);
				return "注册成功：用户名=" + u + ", 密码=" + p;
			}
		});

	}
}
